package com.jh.user.business.impl;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.BeanUtil;
import cn.jh.common.utils.CommonConstants;
import com.jh.user.business.CongMingChannelBusiness;
import com.jh.user.pojo.CongMingChannel;
import com.jh.user.pojo.CongMingChannelRequest;
import com.jh.user.repository.CongMingChannelRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.Map;

@Service
public class CongMingChannelBusinessImpl implements CongMingChannelBusiness {

    private static final Logger log = LoggerFactory.getLogger(CongMingChannelBusinessImpl.class);

    @Autowired
    private CongMingChannelRepository congMingChannelRepository;
    @Autowired
    private EntityManager entityManager;

    @Override
    @Transactional
    public Map<String, Object> saveOfUpdateChannelInfo(CongMingChannel congMingChannel, CongMingChannelRequest channelRequest, String operating) throws ServiceException {
        CongMingChannel cmc = null;
        // 新增
        if (CommonConstants.CHANNEL_ADD.equals(operating)) {
            // 1、判断该通道是否已经存在
            String channelNo = congMingChannel.getChannelNo();
            String channelTag = congMingChannel.getChannelTag();
            List<CongMingChannel> all = congMingChannelRepository.findAll();
            for (CongMingChannel mingChannel : all) {
                String existChannelTag = mingChannel.getChannelTag();
                String existChannelNo = mingChannel.getChannelNo();
                if (channelNo.equals(existChannelNo) || channelTag.equals(existChannelTag)) {
                    throw new ServiceException("添加失败，通道商家标号或通道标识已存在！");
                }
            }
            // 2、新增
            congMingChannel.addCongMingChannel(channelRequest);
            cmc = congMingChannelRepository.save(congMingChannel);
            entityManager.flush();
        }
        // 修改
        if (CommonConstants.CHANNEL_MODIFY.equals(operating)) {
            String channelNo = channelRequest.getChannelNo();
            cmc = congMingChannelRepository.getByChannelNo(channelNo);
            if (null == cmc) {
                throw new ServiceException("无法修改，通道商家标号不存在！");
            }
            congMingChannel.setId(cmc.getId());
            BeanUtil.copyPropertiesIgnoreNull(congMingChannel, cmc);
            entityManager.merge(cmc);
            entityManager.flush();
        }
        return cmc.getCongMingChannelInfo();
    }
}
